package com.unism.uniMeterage.meterage.stream.version1_1;

import com.unism.uniMeterage.meterage.stream.Message;
import com.unism.uniMeterage.meterage.stream.MessageEvent;
import com.unism.uniMeterage.meterage.stream.MessageListener;
import com.unism.uniMeterage.meterage.stream.Worker;

import java.util.LinkedList;
import java.util.List;

/**
 * @author liuc
 * 系统默认的消息格式
 */
public class DefaultMessage implements Message{

    private List<MessageListener> listeners = new LinkedList<MessageListener>();
    private  Worker source;
    private String subject;
    private  Object data;

    public DefaultMessage(Worker source, String subject, Object data) {
        this.source = source;
        this.subject = subject;
        this.data = data;
    }
    @Override
    public Worker getSource() {
        return  this.source;
    }
    @Override
    public String getSubject() {
        return this.subject;
    }
    @Override
    public Object getData() {
        return this.data;
    }

    /**
     * 添加监听器
     * @param l
     */
    public void addMessageListener(MessageListener l) {
        if (!listeners.contains(l)) {
            listeners.add(l);
        }
    }

    /**
     * 移除监听器
     * @param l
     */
    public void removeMessageListener(MessageListener l) {
        listeners.remove(l);
    }

    /**
     * 触发监听器
     * @param e
     */
    public void triggerListeners(MessageEvent e) {
        for(MessageListener l : listeners) {
            l.doMessage(e);
        }
    }
    public void setSource(Worker source) {
        this.source = source;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setData(Object data) {
        this.data = data;
    }
}
